﻿var fs = require("fs");
var formidable = require('formidable'),
    http = require('http'),
    util = require('util');

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
      var form = new formidable.IncomingForm({
      encoding:"utf-8",
      uploadDir:"./upload_tmp",  //文件上传地址
      keepExtensions:true  //保留后缀
    });

  //   var form = new multiparty.Form({
  //     encoding:"utf-8",
  //     uploadDir:"./upload_tmp",  //文件上传地址
  //     keepExtensions:true  //保留后缀
  //  })
  
    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(util.inspect({fields: fields, files: files}));

      var obj ={};
      Object.keys(fields).forEach(function(name) {
          //console.log('name:' + name+";filed:"+fields[name]);
          obj[name] = fields[name];
      });
  
      Object.keys(files).forEach(function(name) {
          console.log('name:' + name+";file:"+files[name].path);
          obj[name] = files[name];
          let timestamps = Math.round(new Date().getTime() / 1000).toString();
          let newPath='./upload_tmp/'+timestamps+files[name].name;
          fs.rename(files[name].path, newPath, function (err) {
          if(err)
          {
            var result = {
                status: 0,
                message: "上传失败",
                data: err
            }
            res.end(result);
          }else
          {
              var result = {
                status: 1,
                message: "上传成功",
                data: files[name].name
                }
            res.end(result);
          }      
      }) 

          console.log(files[name].path);
      });

      //var oldName = files.file.path;
      

    });
   
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" '+
    'method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(8888);